import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useSelectionStore = defineStore('selection', () => {
  // 选择状态
  const selectedObjects = ref([])
  const hoveredObject = ref(null)
  const selectionMode = ref('single') // single, multiple, box
  const isSelecting = ref(false)

  // 选择框状态
  const selectionBox = ref({
    start: { x: 0, y: 0 },
    end: { x: 0, y: 0 },
    visible: false
  })

  // 计算属性
  const hasSelection = computed(() => selectedObjects.value.length > 0)
  const selectionCount = computed(() => selectedObjects.value.length)
  const isMultipleSelection = computed(() => selectedObjects.value.length > 1)
  const selectionBounds = computed(() => {
    if (selectedObjects.value.length === 0) return null
    
    // 计算选择对象的边界框
    let minX = Infinity, minY = Infinity
    let maxX = -Infinity, maxY = -Infinity
    
    selectedObjects.value.forEach(obj => {
      minX = Math.min(minX, obj.x)
      minY = Math.min(minY, obj.y)
      maxX = Math.max(maxX, obj.x + obj.width)
      maxY = Math.max(maxY, obj.y + obj.height)
    })
    
    return {
      x: minX,
      y: minY,
      width: maxX - minX,
      height: maxY - minY
    }
  })

  // Actions
  const selectObject = (object, addToSelection = false) => {
    if (!addToSelection) {
      selectedObjects.value = [object]
    } else {
      if (!selectedObjects.value.find(obj => obj.id === object.id)) {
        selectedObjects.value.push(object)
      }
    }
  }

  const selectObjects = (objects) => {
    selectedObjects.value = [...objects]
  }

  const deselectObject = (objectId) => {
    selectedObjects.value = selectedObjects.value.filter(obj => obj.id !== objectId)
  }

  const deselectAll = () => {
    selectedObjects.value = []
  }

  const toggleSelection = (object) => {
    const index = selectedObjects.value.findIndex(obj => obj.id === object.id)
    if (index >= 0) {
      selectedObjects.value.splice(index, 1)
    } else {
      selectedObjects.value.push(object)
    }
  }

  const selectInBox = (start, end) => {
    // 框选逻辑
    const minX = Math.min(start.x, end.x)
    const maxX = Math.max(start.x, end.x)
    const minY = Math.min(start.y, end.y)
    const maxY = Math.max(start.y, end.y)
    
    // 这里需要从其他store获取所有对象进行碰撞检测
    // const allObjects = getObjectsInBounds({ x: minX, y: minY, width: maxX - minX, height: maxY - minY })
    // selectedObjects.value = allObjects
  }

  const setHoveredObject = (object) => {
    hoveredObject.value = object
  }

  const clearHoveredObject = () => {
    hoveredObject.value = null
  }

  const startSelectionBox = (x, y) => {
    selectionBox.value.start = { x, y }
    selectionBox.value.end = { x, y }
    selectionBox.value.visible = true
    isSelecting.value = true
  }

  const updateSelectionBox = (x, y) => {
    if (isSelecting.value) {
      selectionBox.value.end = { x, y }
    }
  }

  const endSelectionBox = () => {
    if (isSelecting.value) {
      selectInBox(selectionBox.value.start, selectionBox.value.end)
      selectionBox.value.visible = false
      isSelecting.value = false
    }
  }

  const cancelSelectionBox = () => {
    selectionBox.value.visible = false
    isSelecting.value = false
  }

  const setSelectionMode = (mode) => {
    selectionMode.value = mode
  }

  const moveSelection = (deltaX, deltaY) => {
    selectedObjects.value.forEach(obj => {
      obj.x += deltaX
      obj.y += deltaY
    })
  }

  const rotateSelection = (angle, center) => {
    selectedObjects.value.forEach(obj => {
      // 计算对象相对于旋转中心的偏移
      const dx = obj.x - center.x
      const dy = obj.y - center.y
      
      // 应用旋转
      const cos = Math.cos(angle)
      const sin = Math.sin(angle)
      obj.x = center.x + dx * cos - dy * sin
      obj.y = center.y + dx * sin + dy * cos
      obj.rotation = (obj.rotation || 0) + angle
    })
  }

  const scaleSelection = (scaleX, scaleY, center) => {
    selectedObjects.value.forEach(obj => {
      // 计算对象相对于缩放中心的偏移
      const dx = obj.x - center.x
      const dy = obj.y - center.y
      
      // 应用缩放
      obj.x = center.x + dx * scaleX
      obj.y = center.y + dy * scaleY
      obj.width *= scaleX
      obj.height *= scaleY
    })
  }

  const duplicateSelection = () => {
    const duplicated = selectedObjects.value.map(obj => ({
      ...obj,
      id: generateId(), // 生成新ID
      x: obj.x + 10, // 稍微偏移
      y: obj.y + 10
    }))
    
    // 这里需要将复制的对象添加到设计数据中
    // addObjects(duplicated)
    
    // 选择复制的对象
    selectObjects(duplicated)
  }

  const deleteSelection = () => {
    const objectIds = selectedObjects.value.map(obj => obj.id)
    // 这里需要从设计数据中删除对象
    // deleteObjects(objectIds)
    
    deselectAll()
  }

  const groupSelection = () => {
    if (selectedObjects.value.length < 2) return
    
    // 创建组
    const group = {
      id: generateId(),
      type: 'group',
      children: selectedObjects.value.map(obj => obj.id),
      ...selectionBounds.value
    }
    
    // 这里需要将组添加到设计数据中
    // addGroup(group)
    
    // 选择组
    selectObject(group)
  }

  const ungroupSelection = () => {
    // 取消组的逻辑
    selectedObjects.value.forEach(obj => {
      if (obj.type === 'group') {
        // 这里需要取消组并选择子对象
        // ungroup(obj.id)
      }
    })
  }

  const alignSelection = (alignment) => {
    if (selectedObjects.value.length < 2) return
    
    const bounds = selectionBounds.value
    const actions = {
      left: (obj) => obj.x = bounds.x,
      center: (obj) => obj.x = bounds.x + bounds.width / 2 - obj.width / 2,
      right: (obj) => obj.x = bounds.x + bounds.width - obj.width,
      top: (obj) => obj.y = bounds.y,
      middle: (obj) => obj.y = bounds.y + bounds.height / 2 - obj.height / 2,
      bottom: (obj) => obj.y = bounds.y + bounds.height - obj.height
    }
    
    if (actions[alignment]) {
      selectedObjects.value.forEach(actions[alignment])
    }
  }

  const distributeSelection = (distribution) => {
    if (selectedObjects.value.length < 3) return
    
    const sorted = [...selectedObjects.value].sort((a, b) => {
      if (distribution === 'horizontal') return a.x - b.x
      return a.y - b.y
    })
    
    const first = sorted[0]
    const last = sorted[sorted.length - 1]
    const totalSpace = distribution === 'horizontal' 
      ? last.x - first.x 
      : last.y - first.y
    const spacing = totalSpace / (sorted.length - 1)
    
    for (let i = 1; i < sorted.length - 1; i++) {
      if (distribution === 'horizontal') {
        sorted[i].x = first.x + spacing * i
      } else {
        sorted[i].y = first.y + spacing * i
      }
    }
  }

  const reset = () => {
    selectedObjects.value = []
    hoveredObject.value = null
    selectionMode.value = 'single'
    isSelecting.value = false
    selectionBox.value = {
      start: { x: 0, y: 0 },
      end: { x: 0, y: 0 },
      visible: false
    }
  }

  // 辅助函数
  const generateId = () => {
    return Date.now().toString(36) + Math.random().toString(36).substr(2)
  }

  return {
    // 状态
    selectedObjects,
    hoveredObject,
    selectionMode,
    isSelecting,
    selectionBox,
    
    // 计算属性
    hasSelection,
    selectionCount,
    isMultipleSelection,
    selectionBounds,
    
    // Actions
    selectObject,
    selectObjects,
    deselectObject,
    deselectAll,
    toggleSelection,
    selectInBox,
    setHoveredObject,
    clearHoveredObject,
    startSelectionBox,
    updateSelectionBox,
    endSelectionBox,
    cancelSelectionBox,
    setSelectionMode,
    moveSelection,
    rotateSelection,
    scaleSelection,
    duplicateSelection,
    deleteSelection,
    groupSelection,
    ungroupSelection,
    alignSelection,
    distributeSelection,
    reset
  }
})
